teamcity.Loader = function(json) {
    this.loaded_ = false;
    this.json = json;
};

teamcity.Loader.prototype.createXMLHttpRequest = function() {
    try {
        return new XMLHttpRequest();
    } catch(e) {
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    }
    alert("XMLHttpRequest not supported");
    return null;
};

teamcity.Loader.prototype.load = function() {
    if (!this.loaded_) {
        this.loaded_ = true;
        var xhReq = this.createXMLHttpRequest();
        xhReq.open("get", this.json["@href"], true);
        xhReq.setRequestHeader('Accept', 'application/json');
        xhReq.send();
        var requestTimer = setTimeout(function() {
            xhReq.abort();
        }, 10000);
        xhReq.onreadystatechange = this.onReadyStateChange_.bind(this, xhReq, requestTimer);
    };
};

teamcity.Loader.prototype.onReadyStateChange_ = function(xhReq, requestTimer) {
    if (xhReq.readyState != 4) {
        return;
    }
    clearTimeout(requestTimer);
    if (xhReq.status != 200) {
        // Handle error, e.g. Display error message on page
        return;
    }
    var serverResponse = xhReq.responseText;
    this.onLoaded(eval("(" + serverResponse + ")"));
}
